package com.datounet.flutterapp;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviType;
import com.amap.api.navi.AmapPageType;
import com.datounet.flutterapp.Bean.BeanLatLngMsg;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MapActivity extends AppCompatActivity {

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventLatLngMsg event) {
        showMarkers(event.latLngList);
    }

    private ImageButton btnBack;
    private Button btnPathPlanning;
    private MapView mMapView;
    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private UiSettings mUiSettings;
    private List<LatLng> points = new ArrayList<>();
    private List<Marker> markers = new ArrayList<>();
    private LatLng centerP;


    public static void showMapAct(Context context) {
        Intent intent = new Intent(context, MapActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        btnBack = findViewById(R.id.act_map_btn_back);
        btnPathPlanning = findViewById(R.id.act_map_btn_path_planning);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btnPathPlanning.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MapActivity.this, "暂未开放", Toast.LENGTH_SHORT).show();
                return;

//                if (LatLngList == null || LatLngList.size() <= 0) {
//                    Toast.makeText(MapActivity.this, "暂无坐标点", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                if (LatLngList.size() >= 17) {
//                    AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
//                    builder.setTitle("途经点超过16个，多余点位将舍弃，确定规划路线？");
//                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            // TODO Auto-generated method stub
//                            pathPlanning();
//                        }
//                    });
//                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            // TODO Auto-generated method stub
////                        setTitle("点击了取消按钮");
//                        }
//                    });
//                    builder.create().show();
//                }
//                pathPlanning();

            }
        });

        initMAP(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    private void initMAP(Bundle savedInstanceState) {
        mMapView = (MapView) findViewById(R.id.map_map_act);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        aMap = mMapView.getMap();
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);
//        mUiSettings.setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。

        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        // myLocationStyle myLocationIcon(BitmapDescriptor myLocationIcon);//设置定位蓝点的icon图标方法，需要用到BitmapDescriptor类对象作为参数。
        myLocationStyle.interval(5 * 1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                centerP=new LatLng(location.getLatitude(), location.getLongitude());
//                zoomCamera(centerP, points);
            }
        });
//        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
//            @Override
//            public boolean onMarkerClick(Marker marker) {
//                Toast.makeText(MapActivity.this, marker.getPosition().toString(), Toast.LENGTH_SHORT).show();
//                return false;
//            }
//        });
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
//                Toast.makeText(MapActivity.this, marker.getPosition().toString(), Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
                builder.setTitle("确认导航至：" + marker.getSnippet());
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        AmapNaviParams params = new AmapNaviParams(null, null, new Poi(null, marker.getPosition(), null), AmapNaviType.DRIVER, AmapPageType.NAVI);
                        params.setNeedDestroyDriveManagerInstanceWhenNaviExit(true);
                        //启动导航组件
                        AmapNaviPage.getInstance().showRouteActivity(MyApplication.getInstance(), params, null);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
//                        setTitle("点击了取消按钮");
                    }
                });
                builder.create().show();
            }

        });

    }

    private void zoomCamera(LatLng centerP, List<LatLng> points) {
        if (aMap == null || centerP == null || points == null) {
            return;
        }
        LatLngBounds.Builder boundsBuilder = LatLngBounds.builder();

        for (LatLng p : points) {
            LatLng p1 = new LatLng((centerP.latitude * 2) - p.latitude, (centerP.longitude * 2) - p.longitude);
            boundsBuilder.include(p);
            boundsBuilder.include(p1);
        }

        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 50));

    }

    private void showMarkers(List<BeanLatLngMsg> LatLngList) {
        if (aMap == null) {
            return;
        }

        points.clear();
        for (Marker marker : markers) {
            marker.remove();
        }
        markers.clear();

        for (BeanLatLngMsg detail : LatLngList) {

//                        LatLngList.add(new BeanActiveOrdersLatLng.LatLngDetail("北二路庐山路","118.581927","37.476799"));
//            points.add(new LatLng(37.476799,118.581927 ));
//            MarkerOptions options = new MarkerOptions();
//            options.title("北二路庐山路").
////                    snippet(p.getAdderss()).
//        position(new LatLng(37.476799, 118.581927));
//            options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_map_customer)));
//
//            markers.add(aMap.addMarker(options));



            points.add(new LatLng(detail.getLatitude(), detail.getLongitude()));
            MarkerOptions options = new MarkerOptions();
            options.title(detail.getUser_name()).
//                    snippet(p.getAdderss()).
        position(new LatLng(detail.getLatitude(), detail.getLongitude()));
            options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_map_customer)));

            markers.add(aMap.addMarker(options));
        }
        zoomCamera(centerP, points);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}